//
//  CGDOperationsVC.swift
//  BWToolKit_Example
//
//  Created by zhuxuhong on 2022/3/21.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import BWToolKit
import UIKit

class GCDOperationsVC: UIViewController {
    @IBOutlet weak var label: UILabel!
    
    lazy var ops: [GCD.Task.Operation] = (1...10).map
    { i in
        let op = GCD.Task.Operation(taskId: .init(i), timeout: 3)
        op.handler =  { [weak self, weak op] in
            guard let strongSelf = self, let strongOp = op else { return }
            strongSelf.request(task: i, time: Double(i), completion: {
                strongSelf.label.text = "Finished: \(strongOp.taskId) ... ✅✅✅✅✅✅✅✅✅✅✅"
                GCD.asyncAfter(seconds: 1, handler: strongOp.completionBlock ?? {})
            })
        }
        return op
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        GCD.Task.async(
            operations: ops,
            queuePolicy: .serial,
            timeoutPolicy: .cancelOthers
        ) { [weak self] result in
            guard let self = self else {
                return
            }
            print("Tasks completed with result: \(result)")
            self.view.backgroundColor = result.isAllSuccess ? .systemGreen : .systemRed
        }
        ops[5].cancel()
        ops[6].cancel()
        ops[7].cancel()
    }
    
    func request(task: Int, time: TimeInterval, completion: (()->Void)?) {
        DispatchQueue.global().async { [weak self] in
            GCD.asyncInMainQueue {
                self?.label.text = "Started: \(task) ... ➡️➡️➡️➡️➡️➡️"
            }
            GCD.asyncAfter(seconds: time, in: .main, handler: completion ?? {})
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        GCD.Task.cancel(ops)
    }
    
}
